//
//  ChatToolView.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/28.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit
import RxSwift


class ChatToolView: UIView {
    lazy var switchBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setBackgroundImage(R.image.chat_btn_emoji(), for: .normal)
        btn.setBackgroundImage(R.image.chat_btn_keyboard(), for: .selected)
        btn.layer.cornerRadius = 16
        btn.layer.masksToBounds = true
        btn.rx.tap.subscribe(onNext: { [weak btn] _ in
            guard let btn = btn else { return }
            btn.isSelected = !btn.isSelected
        }).disposed(by: bag)
        return btn
    }()
    
    lazy var chatTV: UITextView = {
        let tv = UITextView()
        tv.layer.cornerRadius = 5
        tv.layer.masksToBounds = true
        tv.font = UIFont.systemFont(ofSize: 15)
        tv.showsVerticalScrollIndicator = true
        tv.contentInsetAdjustmentBehavior = .never
        return tv
    }()
    
    lazy var sendBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("发送", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = .standardColor
        btn.layer.cornerRadius = 4
        btn.layer.masksToBounds = true
        btn.rx.tap.map { [weak self] in
            self?.chatTV.text ?? ""
        }
        .do(onNext: { [weak self] _ in
            self?.chatTV.text = nil
        })
        .bind(to: sendSubject)
        .disposed(by: bag)
        return btn
    }()
    
    private let bag = DisposeBag()
    
    let sendSubject = PublishSubject<String>()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        chatTV.rx.text.orEmpty.map { $0.count > 0 }.bind(to: sendBtn.rx.isEnableTap).disposed(by: bag)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

private extension ChatToolView {
    func setupUI() {
        addSubview(switchBtn)
        switchBtn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(8)
            make.bottom.equalToSuperview().offset(-5)
            make.width.height.equalTo(32)
        }
        addSubview(sendBtn)
        sendBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-8)
            make.bottom.equalTo(switchBtn)
            make.width.equalTo(60)
            make.height.equalTo(34)
        }
        addSubview(chatTV)
        chatTV.snp.makeConstraints { (make) in
            make.left.equalTo(switchBtn.snp.right).offset(8)
            make.right.equalTo(sendBtn.snp.left).offset(-8)
            make.top.equalToSuperview().offset(5)
            make.bottom.equalTo(switchBtn)
        }
    }
}
